import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

/**
 * This is the default implementation of {@link CSVCustomerSerializer}. It
 * serializes a customer object in the following way:
 * <p>
 * id;gender;lastname;firstname;status;birthday;turnoverexpectancy;turnover
 * <p>
 * You are free to choose the seperator.
 */
public class DefaultCSVCustomerSerializer implements CSVCustomerSerializer {
	private final String lineSeperator = System.getProperty("line.separator");
	private final String seperator; // usually ";"

	public DefaultCSVCustomerSerializer(String seperator) {
		this.seperator = seperator;
	}

	@Override
	public String serializeCustomer(Customer customer) {
		// We create a StringBuffer which will save all the different substrings
		StringBuilder sb = new StringBuilder();
		sb.append(customer.getId());
		sb.append(seperator);
		sb.append(customer.getGender().name());
		sb.append(seperator);
		sb.append(customer.getLastName());
		sb.append(seperator);
		sb.append(customer.getFirstName());
		sb.append(seperator);
		sb.append(customer.getStatus());
		sb.append(seperator);

		SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyy");
		sb.append(dateFormat.format(customer.getBirthday()));

		sb.append(seperator);
		sb.append(customer.getTurnoverExpectancy());
		sb.append(seperator);
		sb.append(customer.getTurnover());
		// At the end we use the StringBuffer to create one single string which
		// consists of all
		// the different strings before
		return sb.toString();
	}

	@Override
	public String serializeCustomers(List<Customer> customers) {
		StringBuilder sb = new StringBuilder();

		for (Customer customer : customers) {
			sb.append(serializeCustomer(customer));
			sb.append(lineSeperator);
		}

		return sb.toString();
	}

	@Override
	public Customer readLine(String line) throws IllegalArgumentException {
		StringTokenizer st = new StringTokenizer(line, seperator);
		if (st.countTokens() != 8) {
			throw new IllegalArgumentException(
					"The string is not a valid csv string.");
		}

		int id = Integer.parseInt(st.nextToken());
		Gender gender = Gender.valueOf(st.nextToken());
		String surname = st.nextToken();
		String forename = st.nextToken();
		Status status = Status.valueOf(st.nextToken());

		String dateString = st.nextToken();
		Date date = null;
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyy");
			date = dateFormat.parse(dateString);
		} catch (ParseException e) {
			throw new IllegalArgumentException(
					"Error while parsing the csv string");
		}

		int turnoverExpectancy = Integer.parseInt(st.nextToken());
		int turnover = Integer.parseInt(st.nextToken());

		return new Customer(id, gender, surname, forename, status, date,
				turnoverExpectancy, turnover);
	}
}
